﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using umbraco.cms.businesslogic.member;
using umbraco.controls;
using umbraco.interfaces;

namespace netaddICTs.Umb.ProtectedMedia.Datatypes.MultipleMemberGroupPicker {

    public sealed class DataEditor : UpdatePanel, IDataEditor {
    
        private readonly IData _data;
        private XmlDocument _xmlDocument;
        private DualSelectbox _memberGroupPicker;

        public DataEditor(IData data) {
            _data = data;
        }

        #region IDataEditor Members

        public bool TreatAsRichTextEditor {
            get { return false; }
        }

        public bool ShowLabel {
            get { return false; }
        }

        public Control Editor {
            get { return this; }
        }

        public void Save() {
            var doc = CreateBaseXmlDocument();
            var root = doc.DocumentElement;

            foreach (var groupName in _memberGroupPicker.Value.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)) {
                var newNode = doc.CreateElement("memberGroup");
                var idAttribute = doc.CreateNode(XmlNodeType.Attribute, "id", null);

                idAttribute.Value = MemberGroup.GetByName(groupName).Id.ToString();
                newNode.Attributes.SetNamedItem(idAttribute);

                if (root != null) root.AppendChild(newNode);
            }

            _data.Value = doc.InnerXml;
        }

        #endregion

        //Draws the controls, only gets called for the first drawing of the page, not for each postback
        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            try {
                _xmlDocument = new XmlDocument();
                _xmlDocument.LoadXml(_data.Value.ToString());
            }
            catch {
                _xmlDocument = CreateBaseXmlDocument();
            }

            var allGroups = MemberGroup.GetAll;
            var selectedGroups = "";

            _memberGroupPicker = new DualSelectbox {ID = "_memberGroupPicker", Rows = 10, Width = 300};

            foreach (var group in allGroups) {
                var listItem = new ListItem(group.Text, group.Text);

                if (_xmlDocument.DocumentElement != null) {
                    foreach (XmlNode node in _xmlDocument.DocumentElement.ChildNodes) {
                        var groupNodeId = int.Parse(node.Attributes["id"].Value);
                        var groupName = GetGroupNameBasedOnId(allGroups, groupNodeId);

                        if (Page.IsPostBack) continue;
                        if (groupName == group.Text)
                            selectedGroups += groupName + ",";
                    }
                }
                _memberGroupPicker.Items.Add(listItem);
            }

            _memberGroupPicker.Value = selectedGroups;

            ContentTemplateContainer.Controls.Add(_memberGroupPicker);
        }

        protected override void Render(HtmlTextWriter writer) {
            _memberGroupPicker.RenderControl(writer);
        }

        private static XmlDocument CreateBaseXmlDocument() {
            var doc = new XmlDocument();
            XmlNode root = doc.CreateElement("memberGroups");
            doc.AppendChild(root);

            return doc;
        }

        private static string GetGroupNameBasedOnId(IEnumerable<MemberGroup> allGroups, int groupId) {
            foreach (var group in allGroups) {
                if (group.Id == groupId)
                    return group.Text;
            }
            return string.Empty;
        }
    }
}